import { createStore } from "vuex";
import createPersistedState from "vuex-persistedstate";

import { menus } from "@/router/index.js";

function filterRoutes(menus, roles) {
    // 最终返回结果
    let result = [];
    menus.forEach((route) => {
        // 拷贝一份对象
        const tmp = { ...route };
        if (roles.includes(tmp.name)) {
            // 是否有 children
            if (tmp.children) {
                tmp.children = filterRoutes(tmp.children, roles);
            }

            result.push(tmp);
        }
    });

    return result;
}

const store = createStore({
    state: {
        // 登录用户名
        username: "",
        // 页面权限: ['home', 'banner-list', 'banner']
        pageRoles: [],
        // 用户角色 1 - 管理员  2 - 超级管理员
        role: "",
        sex: "",

        // 左侧菜单是否收起
        isFold: false,
    },

    getters: {
        /**
         * 当前用户有权限访问的路由页面routes
         */
        permissionRoutes(state) {
            console.log("hello");
            const arr = menus.filter((item) => !item.hidden);
            if (state.role === 2) {
                // 超级管理员
                return arr;
            } else {
                // 普通管理员
                return filterRoutes(arr, state.pageRoles);
            }
        },
    },

    mutations: {
        setUsername(state, username) {
            state.username = username;
            state.sex = "女";

            // localStorage.setItem("username", username);
        },

        setState(state, payload) {
            state.username = payload.adminname;
            state.pageRoles = payload.checkedkeys;
            state.role = payload.role;
        },

        toggleIsFold(state) {
            state.isFold = !state.isFold;
        },
    },

    plugins: [
        createPersistedState({
            // 额外配置
            // 指定本地存储使用什么： 默认是 window.localStorage
            // storage: window.sessionStorage,
            // 指定只对那些 state 做存储, 默认是 全部存储
            // reducer: (state) => {
            //   return {
            //     username: state.username,
            //   };
            // },
        }),
    ],
});

export default store;
